package com.howtodoinjava.services;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.howtodoinjava.dao.UserDAO;
import com.howtodoinjava.entity.User;
import com.howtodoinjava.entity.UserRole;

@Service
public class UserServicesImpl implements UserService {

	@Autowired
	UserDAO userDao;

	@Autowired
	PasswordEncoder passwordEncoder;

	@Transactional(readOnly = false)
	public User getUserByName(String userName) {
		return userDao.getUserByName(userName);
	}

	public UserDetails getUserDetails(String userName) {
		User user = userDao.getUserByName(userName);
		List<GrantedAuthority> authorities = buildUserAuthority(user
				.getUserRole());
		return buildUserForAuthentication(user, authorities);
	}

	@Transactional
	public void insertUser(User user) {
		String newPassword = passwordEncoder.encodePassword(user.getPassword(),
				null);
		user.setPassword(newPassword);
		userDao.insertUser(user);
	}

	@Transactional
	public void updateUser(User user) {
		// TODO Auto-generated method stub

	}

	@Transactional
	public void deleteUser(User user) {
		// TODO Auto-generated method stub

	}

	@Transactional
	public void deleteUser(int userId) {
		// TODO Auto-generated method stub
	}

	private UserDetails buildUserForAuthentication(User user,
			List<GrantedAuthority> authorities) {
		return new org.springframework.security.core.userdetails.User(
				user.getUserName(), user.getPassword(), user.getEnabled(),
				true, true, true, authorities);
	}

	private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
		Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();

		// Build user's authorities
		for (UserRole userRole : userRoles) {
			setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
		}
		List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(
				setAuths);
		return result;
	}

}
